/*
 * @Date: 2022-12-24 00:41:55
 * @LastEditors: 旧轩00°°
 * @LastEditTime: 2022-12-30 13:38:43
 * @FilePath: /vue3-ts-vite-pinia-husky/src/router/index.ts
 */
import { defaultSetting } from '@/config/setting'
import { cache } from '@/utils'
import { createRouter, createWebHistory, type RouteRecordRaw } from 'vue-router'

/**
 * 动态路由
 * 用来放置有权限（roles 属性）的路由
 * 必须带有 name 属性
 */
export const asyncRoutes: any = [
  {
    path: '/analysis',
    name: '系统总览',
    meta: { title: '系统总览', icon: 'menu-monitor' },
    children: [
      {
        path: '/analysis/overview',
        name: '核心技术',
        meta: { title: '核心技术' }
      },
      {
        path: '/analysis/dashboard',
        name: '商品统计',
        meta: { title: '商品统计' }
      }
    ]
  },
  {
    path: '/system',
    name: '系统管理',
    meta: { title: '系统管理' },
    children: [
      {
        path: '/system/users',
        name: '用户管理'
      },
      {
        path: '/system/roles',
        name: '角色管理'
      }
    ]
  }
]

// 常量理由
const constantRoutes: RouteRecordRaw[] = [
  {
    path: '/',
    redirect: '/login'
  },
  {
    path: '/login',
    name: 'login',
    component: () => import('../views/login/login-theme-1/index.vue')
  }
]

// 全部路由
export const allRoutes: any = [
  {
    path: '/analysis',
    name: '系统总览',
    meta: { title: '系统总览' },
    children: [
      {
        path: '/analysis/overview',
        name: '核心技术',
        meta: { title: '核心技术' },
        component: () => import('@/views/main/analysis/overview/index.vue')
      },
      {
        path: '/analysis/dashboard',
        name: '商品统计',
        meta: { title: '商品统计' },
        component: () => import('@/views/main/analysis/dashboard/index.vue')
      }
    ]
  },
  {
    path: '/system',
    name: '系统管理',
    meta: { title: '系统管理' },
    children: [
      {
        path: '/system/users',
        name: '用户管理'
      },
      {
        path: '/system/roles',
        name: '角色管理'
      }
    ]
  }
]

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    ...constantRoutes,
    {
      path: '/main',
      name: 'main',
      component: () => import('../views/main/index.vue'),
      children: []
    }
  ]
})

router.beforeEach((to, from) => {
  const token = cache.getCache(defaultSetting.TOKEN)
  if (to.path.startsWith('/main') && !token) {
    return '/login'
  }
})

export default router
